import json
import os


def convert_to_seconds(time_str):
    """Converts time string in "mm:ss" format to seconds."""
    split_list = time_str.split(":")
    if len(split_list) != 2:
        raise ValueError("Invalid time format. Should be 'mm:ss'.")
    minutes, seconds = map(float, split_list)
    return minutes * 60 + seconds


def process_time_json(file_path):
    """Processes the JSON file and prints timestamps in minutes:seconds format."""
    with open(file_path, "r") as f:
        data = json.load(f)
    
    map_tree = dict()
    for scene_data in data:
        scene_name = scene_data["scene"]
        map_tree[scene_name] = dict()
        arrive_time_seconds = convert_to_seconds(scene_data["arrive_time"])
        leave_time_seconds = convert_to_seconds(scene_data["leave_time"])

        print(f"Scene: {scene_name}")
        print(f"  Arrive Time: {arrive_time_seconds:f} s")
        print(f"  Leave Time: {leave_time_seconds:f} s")
        
        # print(f"  Arrive Time: {arrive_time_seconds // 60:02d}:{arrive_time_seconds % 60:02d}")
        # print(f"  Leave Time: {leave_time_seconds // 60:02d}:{leave_time_seconds % 60:02d}")

        for waypoint, time_str in scene_data["waypoints"].items():
            if time_str != "N/A":
                waypoint_time_seconds = convert_to_seconds(time_str)
                map_tree[scene_name][waypoint] = waypoint_time_seconds
                # print(f"    Waypoint '{waypoint}': {waypoint_time_seconds // 60:02d}:{waypoint_time_seconds % 60:02d}")
                print(f"    Waypoint '{waypoint}': {waypoint_time_seconds:f} s")
            else:
                print(f"    Waypoint '{waypoint}': N/A")
    return map_tree


def output_json(map_tree, path):
    """Outputs the map tree as a JSON file."""
    # Replace 'path/to/output.json' with the actual path to save the JSON file
    # 将字典转换为JSON字符串
    json_data = json.dumps(map_tree)
    # 将JSON字符串保存为文件
    with open(path, 'w') as f:
        f.write(json_data)


if __name__ == '__main__':
    # Replace 'path/to/your/file.json' with the actual path to your JSON file
    map_dict = process_time_json(os.path.join(os.path.dirname(__file__), "time.json"))
    output_json(map_dict, os.path.join(os.path.dirname(__file__), "map.json"))
    